package com.iafme.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.zhxu.bs.BeanSearcher;
import cn.zhxu.bs.operator.Contain;
import cn.zhxu.bs.operator.Equal;
import cn.zhxu.bs.util.MapUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iafme.dto.req.CertificateInfoReqDTO;
import com.iafme.dto.res.CertificateInfoResDTO;
import com.iafme.mapper.CertificateInfoMapper;
import com.iafme.model.CertificateInfo;
import com.iafme.service.CertificateInfoService;
import com.systemframework.constants.Constants;
import com.systemframework.exception.ResultException;
import com.systemframework.util.SearchUtl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author summer
 * @version 1.0
 * @date 2025/3/27 11:38
 */
@Service
@Transactional(rollbackFor = Exception.class)
@AllArgsConstructor
public class CertificateInfoServiceImpl extends ServiceImpl<CertificateInfoMapper, CertificateInfo> implements CertificateInfoService {

    private final BeanSearcher beanSearcher;

    @Override
    public Page<CertificateInfoResDTO> lists(CertificateInfoReqDTO reqDTO) {
        Map<String, Object> build = MapUtils.builder().page(reqDTO.getPageNum() - 1, reqDTO.getPageSize())
                .field(CertificateInfoResDTO::getMemberName, reqDTO.getMemberName()).op(Contain.class)
                .field(CertificateInfoResDTO::getCertificateName, reqDTO.getCertificateName()).op(Contain.class)
                .build();
        return SearchUtl.searchDataList(reqDTO.getPageNum(), reqDTO.getPageSize(), beanSearcher.search(CertificateInfoResDTO.class,build));
    }

    @Override
    public List<CertificateInfoResDTO> memberCertificateInfo() {
        Map<String, Object> build = MapUtils.builder()
                .field(CertificateInfoResDTO::getStatus,CertificateInfoResDTO::getMemberId)
                .sql("$1 IS NOT NULL AND $2="+StpUtil.getLoginIdAsInt()).build();
        return beanSearcher.searchAll(CertificateInfoResDTO.class,build);
    }

    @Override
    public void logoutCertificate(Integer id) {
        CertificateInfo certificateInfo = this.getById(id);
        if(ObjectUtil.isEmpty(certificateInfo)){
            throw new ResultException("证书不存在");
        }
        certificateInfo.setStatus(Constants.TWO);
        this.updateById(certificateInfo);
    }
}
